package com.jsftoolkit.utils;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Returns the results of a series of iterators, in the order they were provided
 * to the constructor.
 * 
 * @author noah
 * 
 * @param <T>
 */
public class ConcatenatedIterator<T> implements Iterator<T> {

	private final Iterator<? extends T>[] iterators;

	private int lastReturned;

	private int next;

	public ConcatenatedIterator(final Iterator<? extends T>... iterators) {
		super();
		this.iterators = iterators;
	}

	public boolean hasNext() {
		boolean result = next < iterators.length && iterators[next].hasNext();
		while (!result && next < iterators.length - 1) {
			result = iterators[++next].hasNext();
		}
		return result;
	}

	public T next() {
		// find the next iterator with an element
		if (!hasNext()) {
			throw new NoSuchElementException();
		}
		return iterators[lastReturned = next].next();
	}

	public void remove() {
		iterators[lastReturned].remove();
	}

}
